package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.DBUtil;
import model.Guser;
import model.Job;
import model.Puser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/job-guanli-list.json")
public class guanliJobList extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Guser currentUser = (Guser) session.getAttribute("gcurrentUser");
        Integer guid = currentUser.guid;
        if(guid==null){
            return;
        }
        List<Job> jobList = new ArrayList<>();
        Object result;
        result = new Object(){
            public Object data = jobList;
        };
        try(Connection c = DBUtil.getConnection()){
            String sql = "SELECT * FROM job  ORDER BY puid  DESC";
            try(PreparedStatement s = c.prepareStatement(sql)){
                try (ResultSet rs = s.executeQuery()){
                    while(rs.next()){
                        Job job = new Job();
                        job.puid = rs.getString("puid");
                        job.jid = rs.getString("jid");
                        job.title = rs.getString("title");
                        job.type= rs.getString("type");
                        job.salary = rs.getString("salary");
                        job.contents = rs.getString("contents");
                        jobList.add(job);
                    }
                }
            }
        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}
